from flask import Blueprint, request, jsonify
from app import db
from app.models.sync_log import SyncLog
from app.models.sync_task import SyncTask
from app.models.alert import Alert
from sqlalchemy import func
from datetime import datetime, timedelta

sync_stats_bp = Blueprint('sync_stats', __name__)

@sync_stats_bp.route('/overview', methods=['GET'])
def get_sync_stats_overview():
    """获取同步统计概览"""
    # 获取任务总数
    task_count = SyncTask.query.count()
    
    # 获取运行中的任务数
    running_task_count = SyncTask.query.filter_by(status='running').count()
    
    # 获取今日同步次数
    today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
    today_sync_count = SyncLog.query.filter(SyncLog.start_time >= today).count()
    
    # 获取今日同步数据量
    today_sync_records = SyncLog.query.with_entities(
        func.sum(SyncLog.total_records)
    ).filter(SyncLog.start_time >= today).scalar() or 0
    
    # 获取今日同步成功率
    today_success_rate = 0
    if today_sync_count > 0:
        today_success_records = SyncLog.query.with_entities(
            func.sum(SyncLog.success_records)
        ).filter(SyncLog.start_time >= today).scalar() or 0
        today_success_rate = round(today_success_records / today_sync_records * 100, 2) if today_sync_records > 0 else 0
    
    # 获取未读报警数
    unread_alert_count = Alert.query.filter_by(status='unread').count()
    
    return jsonify({
        'code': 200,
        'data': {
            'task_count': task_count,
            'running_task_count': running_task_count,
            'today_sync_count': today_sync_count,
            'today_sync_records': today_sync_records,
            'today_success_rate': today_success_rate,
            'unread_alert_count': unread_alert_count
        }
    })

@sync_stats_bp.route('/trend', methods=['GET'])
def get_sync_stats_trend():
    """获取同步统计趋势"""
    days = request.args.get('days', 7, type=int)
    task_id = request.args.get('task_id', type=int)
    
    # 获取指定天数的日期范围
    end_date = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
    start_date = end_date - timedelta(days=days-1)
    
    # 准备日期列表和结果数据
    date_list = []
    sync_count_list = []
    success_rate_list = []
    
    # 查询条件
    query = SyncLog.query
    if task_id:
        query = query.filter_by(task_id=task_id)
    
    # 遍历每一天
    current_date = start_date
    while current_date <= end_date:
        next_date = current_date + timedelta(days=1)
        date_list.append(current_date.strftime('%Y-%m-%d'))
        
        # 当天同步次数
        day_sync_count = query.filter(
            SyncLog.start_time >= current_date,
            SyncLog.start_time < next_date
        ).count()
        sync_count_list.append(day_sync_count)
        
        # 当天同步成功率
        day_success_rate = 0
        if day_sync_count > 0:
            day_total_records = query.with_entities(
                func.sum(SyncLog.total_records)
            ).filter(
                SyncLog.start_time >= current_date,
                SyncLog.start_time < next_date
            ).scalar() or 0
            
            day_success_records = query.with_entities(
                func.sum(SyncLog.success_records)
            ).filter(
                SyncLog.start_time >= current_date,
                SyncLog.start_time < next_date
            ).scalar() or 0
            
            day_success_rate = round(day_success_records / day_total_records * 100, 2) if day_total_records > 0 else 0
        
        success_rate_list.append(day_success_rate)
        current_date = next_date
    
    return jsonify({
        'code': 200,
        'data': {
            'dates': date_list,
            'sync_counts': sync_count_list,
            'success_rates': success_rate_list
        }
    })

@sync_stats_bp.route('/failure-reasons', methods=['GET'])
def get_failure_reasons():
    """获取同步失败原因统计"""
    days = request.args.get('days', 7, type=int)
    task_id = request.args.get('task_id', type=int)
    
    # 获取指定天数的日期范围
    end_date = datetime.now()
    start_date = end_date - timedelta(days=days)
    
    # 查询条件
    query = SyncLog.query.filter(
        SyncLog.status == 'failed',
        SyncLog.start_time >= start_date,
        SyncLog.start_time <= end_date
    )
    
    if task_id:
        query = query.filter_by(task_id=task_id)
    
    # 获取失败日志
    failed_logs = query.all()
    
    # 统计失败原因
    failure_reasons = {}
    for log in failed_logs:
        reason = log.error_message or '未知错误'
        # 简化错误消息，只取第一行或前50个字符
        reason = reason.split('\n')[0][:50]
        if reason in failure_reasons:
            failure_reasons[reason] += 1
        else:
            failure_reasons[reason] = 1
    
    # 转换为列表并按出现次数排序
    result = [{'reason': reason, 'count': count} for reason, count in failure_reasons.items()]
    result.sort(key=lambda x: x['count'], reverse=True)
    
    return jsonify({
        'code': 200,
        'data': result
    })

@sync_stats_bp.route('/alerts', methods=['GET'])
def get_alerts():
    """获取报警信息"""
    status = request.args.get('status')
    task_id = request.args.get('task_id', type=int)
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    
    query = Alert.query
    
    if status:
        query = query.filter_by(status=status)
    if task_id:
        query = query.filter_by(task_id=task_id)
    
    alerts = query.order_by(Alert.created_at.desc()).paginate(page=page, per_page=per_page)
    
    return jsonify({
        'code': 200,
        'data': {
            'items': [alert.to_dict() for alert in alerts.items],
            'total': alerts.total,
            'page': alerts.page,
            'pages': alerts.pages,
            'per_page': alerts.per_page
        }
    })

@sync_stats_bp.route('/alerts/<int:id>/read', methods=['PUT'])
def mark_alert_as_read(id):
    """将报警标记为已读"""
    alert = Alert.query.get_or_404(id)
    alert.status = 'read'
    db.session.commit()
    
    return jsonify({
        'code': 200,
        'message': '报警已标记为已读'
    })